package com.att.control;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.RawImage;
import com.android.ddmlib.TimeoutException;
import com.att.control.LinearInterpolator.Callback;
import com.att.control.LinearInterpolator.Point;
import com.sun.image.codec.jpeg.JPEGCodec;




public class AndroidInjector {
	
	private Socket s;
	private BufferedReader br;
	private BufferedWriter bw;
	
	public void touch(int x, int y) throws IOException {
		String cmd =  "tap " + x + " " + y + "\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	//KEYCODE_MENU,KEYCODE_BACK
	public void press(String keycode) throws IOException {
		String cmd = "press " + keycode + "\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	public void touchMove(int x, int y) throws IOException {
		String cmd = "touch move " + x + " " + y + "\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	public void touchDown(int x, int y) throws IOException {
		String cmd = "touch down " + x + " " + y + "\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	public void touchUp(int x, int y) throws IOException {
		String cmd = "touch up " + x + " " + y + "\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	public void quit() throws IOException {
		String cmd = "quit\n";
		bw.write(cmd);
		bw.flush();
		String result = br.readLine();
		System.out.println(result);
	}
	
	public void drag(int startx, int starty, int endx, int endy, int steps, long ms) {
        final long iterationTime = ms / steps;

        LinearInterpolator lerp = new LinearInterpolator(steps);
        LinearInterpolator.Point start = new LinearInterpolator.Point(startx, starty);
        LinearInterpolator.Point end = new LinearInterpolator.Point(endx, endy);
       
        lerp.interpolate(start, end, new Callback() {
            @Override
            public void step(Point point) {
                try {
                	touchMove(point.getX(), point.getY());
                    Thread.sleep(iterationTime);
                } catch (InterruptedException e) {
                	e.printStackTrace();
                } catch (IOException e) {
					e.printStackTrace();
					try {
						quit();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
            }

            @Override
            public void start(Point point) {
                try {
                	touchDown(point.getX(), point.getY());
                	touchMove(point.getX(), point.getY());
                    Thread.sleep(iterationTime);
                } catch (InterruptedException e) {
                	e.printStackTrace();
                } catch (IOException e) {
					e.printStackTrace();
					try {
						quit();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
            }

            @Override
            public void end(Point point) {
            	try {
            		touchMove(point.getX(), point.getY());
                	touchUp(point.getX(), point.getY());
				} catch (IOException e) {
					e.printStackTrace();
					try {
						quit();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
            }
        });
    }
	
	public void type(String text) throws IOException {
		StringTokenizer tok = new StringTokenizer(text, "\n", true);
		while (tok.hasMoreTokens()) {
            String line = tok.nextToken();
            if ("\n".equals(line)) {
              press("enter");
            } else {
            	String command = "type " + line;
            	bw.write(command + "\n");
            	bw.flush();
            	String result = br.readLine();
            	System.out.println(result);
            }
        }
	}
	
	public void connectToDevice() throws UnknownHostException, IOException, InterruptedException {
		Thread.sleep(1500);
		s = new Socket("127.0.0.1", AttMain.action_port);
		br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		
	}
	
	public void takePhoto(String path) throws IOException, TimeoutException, AdbCommandRejectedException {
		IDevice myPhone = AndroidProxy.getInstance().getDevice();
		RawImage raw = myPhone.getScreenshot();
		BufferedImage image = new BufferedImage(raw.width, raw.height,
				BufferedImage.TYPE_INT_RGB);
		int index = 0;
		int indexInc = raw.bpp >> 3;
		for (int y = 0; y < raw.height; y++) {
			for (int x = 0; x < raw.width; x++, index += indexInc) {
				int value = raw.getARGB(index);
				image.setRGB(x, y, value);
			}
		}
		FileOutputStream fos = new FileOutputStream(new File(path));
		JPEGCodec.createJPEGEncoder(fos).encode(image);
		fos.close();
		System.out.println("OK");
	}
}
